package com.labichaoka.chaoka.ui.web;

import android.annotation.TargetApi;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.http.SslError;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.text.TextUtils;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.view.ViewGroup;
import android.webkit.SslErrorHandler;
import android.webkit.WebChromeClient;
import android.webkit.WebResourceError;
import android.webkit.WebResourceRequest;
import android.webkit.WebResourceResponse;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.just.agentweb.AgentWeb;
import com.just.agentweb.DefaultWebClient;
import com.labichaoka.chaoka.BuildConfig;
import com.labichaoka.chaoka.R;
import com.labichaoka.chaoka.base.BaseActivity;
import com.labichaoka.chaoka.base.JsBridgeInterface;
import com.labichaoka.chaoka.utils.SharedPreferencesManager;
import com.labichaoka.chaoka.utils.ToastUtils;
import com.labichaoka.chaoka.widget.TopTitleBar;
import com.umeng.socialize.UMShareAPI;

import butterknife.BindView;
import butterknife.OnClick;


public class WebViewActivity extends BaseActivity {
    @BindView(R.id.tv_title)
    TextView txtTitle;
    @BindView(R.id.close)
    TextView close;
    @BindView(R.id.back_layout)
    RelativeLayout goBack;
    @BindView(R.id.title)
    TopTitleBar title;
    @BindView(R.id.layout)
    LinearLayout linearLayout;

    private String url;
    private AgentWeb mAgentWeb;

    String baseUrl=BuildConfig.WEB_HOST;

    @Override
    protected int initLayoutId() {
        return R.layout.activity_web_view;
    }

    @Override
    protected void initView() {

    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

    @Override
    protected void initData() {
        Bundle bundle = getIntent().getExtras();
        String type = bundle.getString("type");
        if (TextUtils.isEmpty(type)) {
            ToastUtils.show("数据错误,请稍后重试!");
            return;
        }
        switch (type) {
            case "1":
                //运营商认证
                title.setVisibility(View.GONE);
                String extdata = bundle.getString("extdata");
                String backUrl = baseUrl + "blankPage";
                String loginParams = bundle.getString("loginParams");
                if(!BuildConfig.BUILD_TYPE.equals(BuildConfig.TYPE_RELEASE)){
                    //测试
                    url = "https://operator-crawler-test.9fbank.com/#/?appid=00c918a2ab970f568fa62d0fe3ae5045&extdata=" + extdata + "&themeColor=" + "DFBF82" + "&backUrl=" + backUrl + "&loginParams=" + loginParams;
                }else{
                    //正式
                    url="https://h5-opo-cr-pro.9fbank.com/#/?appid=c17a99d3bfb5c7eaa63b28426d931790&extdata="+extdata+"&themeColor="+"DFBF82"+"&backUrl="+backUrl+"&loginParams="+loginParams;
                }
                break;
            case "2":
                //提现
                String keys = bundle.getString("keys");
                url = baseUrl + "withdrawal/sure-order?keys=" + keys + "&token=" + SharedPreferencesManager.getInstance().getString("token", "");
                break;
            case "3":
                //订单详情
                String orderId = bundle.getString("orderId");
                url = baseUrl + "withdrawal/record-order?prevKey=" + orderId + "&token=" + SharedPreferencesManager.getInstance().getString("token", "");
                break;
            case "4":
                //奖励金
                url = baseUrl + "invite-friends/my-invite?token=" + SharedPreferencesManager.getInstance().getString("token", "");
                break;
            case "5":
                //邀请好友
                url = baseUrl + "invite-friends?token=" + SharedPreferencesManager.getInstance().getString("token", "");
                break;
            case "6":
                //在线客服
                break;
            case "7":
                //帮助中心
                url = baseUrl + "my/help-center?token=" + SharedPreferencesManager.getInstance().getString("token", "");
                break;
            case "8":
                url = bundle.getString("url") + "?token=" + SharedPreferencesManager.getInstance().getString("token", "");
                Log.d("url22",url);
                break;
            case "9":
                url = bundle.getString("url");
                Log.d("url22",url);
                break;
            case "10":
                url = bundle.getString("url") + "?token=" + SharedPreferencesManager.getInstance().getString("token", "")+"&phone="+SharedPreferencesManager.getInstance().getString("phone", "");

                break;
            default:
                break;
        }

        mAgentWeb = AgentWeb.with(this)
                .setAgentWebParent(linearLayout, new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT))
                .useDefaultIndicator(getResources().getColor(R.color.mainColor), 3)
                //.setAgentWebWebSettings(getSettings())
                .setWebViewClient(new MyWebViewClient())
                .setWebChromeClient(new MyChromeWebClient())
                //.setPermissionInterceptor(mPermissionInterceptor)
                .setSecurityType(AgentWeb.SecurityType.STRICT_CHECK)
                //.setAgentWebUIController(new UIController(getActivity()))
                .setMainFrameErrorView(R.layout.error_page, -1)
//                .useMiddlewareWebChrome(getMiddlewareWebChrome())
//                .useMiddlewareWebClient(getMiddlewareWebClient())
                .setOpenOtherPageWays(DefaultWebClient.OpenOtherPageWays.DISALLOW)
                .interceptUnkownUrl()
                .createAgentWeb()
                .ready()
                .go(url);

        mAgentWeb.getJsInterfaceHolder().addJavaObject("SuperCard", new JsBridgeInterface(mAgentWeb, this));
        mAgentWeb.getWebCreator().getWebView().getSettings().setUseWideViewPort(true);
        mAgentWeb.getWebCreator().getWebView().getSettings().setAllowFileAccess(true);
    }


    private class MyWebViewClient extends WebViewClient {
        @Override
        public void onPageStarted(WebView view, String url, Bitmap favicon) {
            super.onPageStarted(view, url, favicon);
        }

        @Override
        public void onPageFinished(WebView view, String url) {
            super.onPageFinished(view, url);
        }


        @Override
        public void onReceivedError(WebView view, WebResourceRequest request, WebResourceError error) {
            super.onReceivedError(view, request, error);
        }

        @TargetApi(Build.VERSION_CODES.LOLLIPOP)
        @Override
        public void onReceivedHttpError(WebView view, WebResourceRequest request, WebResourceResponse
                errorResponse) {
            super.onReceivedHttpError(view, request, errorResponse);
        }

        @Override
        public void onReceivedSslError(WebView view, SslErrorHandler handler, SslError error) {
            handler.proceed();
        }

        @Override
        public boolean shouldOverrideUrlLoading(WebView view, WebResourceRequest request) {
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
                view.loadUrl(request.getUrl().toString());
            } else {
                view.loadUrl(request.toString());
            }
            return true;
        }
    }


    private class MyChromeWebClient extends WebChromeClient {
        @Override
        public void onProgressChanged(android.webkit.WebView view, int newProgress) {
            super.onProgressChanged(view, newProgress);
        }

        @Override
        public void onReceivedTitle(WebView view, String title) {
            super.onReceivedTitle(view, title);
            if (title != null && !view.getUrl().contains(title)) {
                if (title.length() > 8) {
                    title = title.substring(0, 8) + "...";
                }
                txtTitle.setText(title);

                if (title.equals("提现申请已提交")) {
                    goBack.setVisibility(View.GONE);
                    close.setVisibility(View.GONE);
                }
            }

            if (view.canGoBack()) {
                if (!TextUtils.isEmpty(title)) {
                    if (!title.equals("提现申请已提交")) {
                        close.setVisibility(View.VISIBLE);
                    }
                }

            } else {
                close.setVisibility(View.GONE);
            }
        }

    }

    @OnClick(R.id.close)
    public void click(View v) {
        finish();
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        return mAgentWeb.handleKeyEvent(keyCode, event) || super.onKeyDown(keyCode, event);
    }


    @Override
    protected void onDestroy() {
        super.onDestroy();
        mAgentWeb.getWebLifeCycle().onDestroy();
    }

    @Override
    protected void onStart() {
        super.onStart();
    }

    @Override
    protected void onPause() {
        super.onPause();
        mAgentWeb.getWebLifeCycle().onPause();
    }

    @Override
    protected void onResume() {
        super.onResume();
        mAgentWeb.getWebLifeCycle().onResume();
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        UMShareAPI.get(this).onActivityResult(requestCode,resultCode,data);
    }
}
